<script setup>
// ------------------------------- 导出和导入 ---------------------------------
// 导入弹窗
import {ref} from "vue";
import {rApi} from "/@/api/support/r-api.js";
import {SmartLoading} from "/@/components/framework/smart-loading/index.js";
import {goodsApi} from "/@/api/business/goods/goods-api.js";
import {message} from "ant-design-vue";
import {smartSentry} from "/@/lib/smart-sentry.js";

const importModalShowFlag = ref(false);

const fileList = ref([]);
// 显示导入
function showImportModal() {
  fileList.value = [];
  importModalShowFlag.value = true;
}

// 关闭 导入
function hideImportModal() {
  importModalShowFlag.value = false;
}

// 从后台下载文件
async function downloadExcel() {
  window.open('http://127.0.0.1:1024/plot.xls');
}

function handleRemove(file) {
  const index = fileList.value.indexOf(file);
  const newFileList = fileList.value.slice();
  newFileList.splice(index, 1);
  fileList.value = newFileList;
}
function beforeUpload(file) {
  fileList.value = [...(fileList.value || []), file];
  return false;
}

async function onImportGoods() {
  const formData = new FormData();
  fileList.value.forEach((file) => {
    formData.append('file', file.originFileObj);
  });

  SmartLoading.show();
  try {
    let res = await rApi.importPlots(formData);
    message.success(res.msg);
  } catch (e) {
    smartSentry.captureError(e);
  } finally {
    SmartLoading.hide();
  }
}
</script>

<template>
  <a-button @click="showImportModal" type="primary" v-privilege="'goods:importGoods'">
    <template #icon>
      <ImportOutlined />
    </template>
    导入
  </a-button>
  <a-modal v-model:open="importModalShowFlag" title="导入" @onCancel="hideImportModal" @ok="hideImportModal">
    <div style="text-align: center; width: 400px; margin: 0 auto">
      <a-button @click="downloadExcel"> <download-outlined />第一步：下载模板</a-button>
      <br />
      <br />
      <a-upload
          v-model:fileList="fileList"
          name="file"
          :multiple="false"
          action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
          accept=".csv"
          :before-upload="beforeUpload"
          @remove="handleRemove"
      >
        <a-button>
          <upload-outlined />
          第二步：选择文件
        </a-button>
      </a-upload>

      <br />
      <a-button @click="onImportGoods">
        <ImportOutlined />
        第三步：开始导入
      </a-button>
    </div>
  </a-modal>
</template>

<style scoped lang="less">

</style>